package com.sduept.nwld.dataserver.manager.fault.tripping;

import com.sduept.bigdata.fault.common.ParamDesc;
import com.sduept.core.ParamManager;
import com.sduept.core.entity.SystemParameter;
import com.sduept.nwld.dataserver.model.tripping.YxBwDetailDTO;
import com.sduept.nwld.dataserver.model.tripping.YxSoeDeatilDTO;
import com.sduept.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author     Author
 * @version    V1.0
 * @Date       2018年8月7日 上午8:38:41
 */
@Service
public class TrippingDetailManager {
	
	@Autowired
	private EmsOracleDAO dao;
	@Autowired
	private ParamManager pc;
	
	/**
	 * 根据变电站查询对应的faceID
	 * @param stationNames
	 * @return Map<变电站名称，FACEID>
	 */
	public Map<String,String> getFaceIds(String[] stationNames){
		Map<String,String> result=new HashMap<String, String>();
		if(stationNames==null||stationNames.length==0){
			return result;
		}
		String sql="SELECT FAC_ID,FAC_NAME FROM EMS.FAC_INFO WHERE FAC_NAME = ? ";
		StringBuilder builder=new StringBuilder();
		for(int i=0;i<stationNames.length-1;i++){
			builder.append(" OR FAC_NAME = ?");
		}
		sql=sql+builder.toString();
		List<?> list = dao.nativeQuery(sql, stationNames);
		if(list.size()==0){
			return result;
		}
		for(Object object:list){
			Object[] objs=(Object[])object;
			if(StringUtils.isEmpty(objs[0].toString())){
				continue;
			}
			result.put(objs[1].toString(), objs[0].toString());
		}
		return result;
	}
	/**
	 * 根据时间以及变电站名称 查询遥信变位信息
	 * @param date
	 * @param stationNames
	 * @return<变电站，集合>
	 */
	public Map<String,List<YxBwDetailDTO>> getBXDetail(Date date,String[] stationNames){
		return getBXDetail(date,stationNames,null);
	}
	/**
	 * 根据时间以及变电站名称 查询遥信变位信息 
	 * @param date
	 * @param stationNames
	 * @param map
	 * @return
	 */
	public Map<String,List<YxBwDetailDTO>> getBXDetail(Date date,String[] stationNames,Map<String, String> map){
		Map<String,List<YxBwDetailDTO>> result=new HashMap<>();
		if(null==map){
			map = getFaceIds(stationNames);
		}
		Date[] dates = getnearlyDates(date);
		String sql="SELECT t.OCCUR_TIME,t.MILLI_SECOND, d.BRK_NAME,DECODE(t.STATUS,2,'合闸','分闸'),t.CONTENT,t.FAC_ID"
				+ " FROM EMS.YX_BW t,EMS.BRK_DEVICE d WHERE SUBSTR(t.YX_ID,2,9) = d.BRK_ID "
				+ " AND t.OCCUR_TIME > TO_DATE ( ? ,'yyyy-mm-dd-hh24-mi-ss') "
				+ " AND t.OCCUR_TIME < TO_DATE ( ? ,'yyyy-mm-dd-hh24-mi-ss') ";
		String tempSql = getFaceIdSql(map.values().size());
		if(StringUtils.isNotEmpty(tempSql)){
			sql=sql+tempSql;
		}
		sql=sql +"ORDER BY t.OCCUR_TIME ASC, t.MILLI_SECOND ASC";
		Object[] params=new Object[map.size()+2];
		if(map.size()!=0){
			String[] array = map.values().toArray(new String[map.size()]);
			for(int i=0;i<array.length;i++){
				params[i+2]=array[i];
			}
		}
		params[0]=DateUtil.getStringDate(dates[0], DateUtil.pattern_ymdhms);
		params[1]=DateUtil.getStringDate(dates[1], DateUtil.pattern_ymdhms);
		List<?> list = dao.nativeQuery(sql, params);
		for(Object obj:list){
			YxBwDetailDTO dto = Object2YxBwDetailDTO(obj);
			String name = getStationName(dto.getFaceId(),map);
			if(StringUtils.isEmpty(name)){
				continue;
			}
			List<YxBwDetailDTO> templist = result.get(name);
			if(templist==null){
				ArrayList<YxBwDetailDTO> dtolist = new ArrayList<YxBwDetailDTO>();
				dtolist.add(dto);
				result.put(name, dtolist);
			}else{
				templist.add(dto);
				result.put(name, templist);
			}
		}
		return result;
	}
	/**
	 * 获取SOE详情
	 * @param date
	 * @param stationNames
	 * @return<变电站，集合>
	 */
	public Map<String,List<YxSoeDeatilDTO>> getSOEDetail(Date date,String[] stationNames){
		return getSOEDetail(date,stationNames,null);
	}
	/**
	 * 获取SOE详情
	 * @param date
	 * @param stationNames
	 * @param map
	 * @return
	 */
	public Map<String,List<YxSoeDeatilDTO>> getSOEDetail(Date date,String[] stationNames,Map<String, String> map){
		Map<String,List<YxSoeDeatilDTO>> result=new HashMap<>();
		if(null==map){
			map = getFaceIds(stationNames);
		}
		Date[] dates = getnearlyDates(date);
		String sql="SELECT t.OCCUR_TIME,t.SOE_TIME,t.MILLI_SECOND,d.BRK_NAME,DECODE(t.STATUS,1,'合闸','分闸'),t.CONTENT,t.FAC_ID "
				+ " FROM EMS.YX_SOE t ,EMS.BRK_DEVICE d WHERE SUBSTR(t.YX_ID,2,9) = d.BRK_ID "
				+ " AND t.OCCUR_TIME > TO_DATE ( ? ,'yyyy-mm-dd-hh24-mi-ss') "
				+ " AND t.OCCUR_TIME < TO_DATE ( ? ,'yyyy-mm-dd-hh24-mi-ss') ";
		String tempSql = getFaceIdSql(map.values().size());
		if(StringUtils.isNotEmpty(tempSql)){
			sql=sql+tempSql;
		}
		sql=sql +"ORDER BY t.SOE_TIME ASC, t.MILLI_SECOND ASC";
		Object[] params=new Object[map.size()+2];
		if(map.size()!=0){
			String[] array = map.values().toArray(new String[map.size()]);
			for(int i=0;i<array.length;i++){
				params[i+2]=array[i];
			}
		}
		params[0]=DateUtil.getStringDate(dates[0], DateUtil.pattern_ymdhms);
		params[1]=DateUtil.getStringDate(dates[1], DateUtil.pattern_ymdhms);
		List<?> list = dao.nativeQuery(sql, params);
		for(Object obj:list){
			YxSoeDeatilDTO dto = Objetc2YxSoeDeatilDTO(obj);
			String name = getStationName(dto.getFaceId(),map);
			if(StringUtils.isEmpty(name)){
				continue;
			}
			List<YxSoeDeatilDTO> templist = result.get(name);
			if(templist==null){
				ArrayList<YxSoeDeatilDTO> dtolist = new ArrayList<YxSoeDeatilDTO>();
				dtolist.add(dto);
				result.put(name, dtolist);
			}else{
				templist.add(dto);
				result.put(name, templist);
			}
		}
		return result;
	}
	private String getStationName(String id,Map<String, String> map){
		String result=null;
		if(StringUtils.isEmpty(id)){
			return result;
		}
		for(Map.Entry<String,String> entry:map.entrySet()){
			if(id.equals(entry.getValue())){
				return entry.getKey();
			}
		}
		return result;
	}
	/**
	 * 根据数据库查出的数据转换为相应的对象
	 * @param obj
	 * @return
	 */
	private YxBwDetailDTO Object2YxBwDetailDTO(Object obj){
		YxBwDetailDTO result=new YxBwDetailDTO();
		Object[] objs=(Object[])obj;
		result.setOccurTime(objs[0]==null?null:(DateUtil.getStringDate((Date)objs[0], DateUtil.pattern_ymdhms)+"."+objs[1].toString()));
		result.setBreakerName(objs[2]==null?null:objs[2].toString());
		result.setActionStatus(objs[3]==null?null:objs[3].toString());
		result.setContent(objs[4]==null?null:objs[4].toString());
		result.setFaceId(objs[5]==null?null:objs[5].toString());
		return result;
	}
	/**
	 * 根据数据库查出的数据转换为相应的对象
	 * @param obj
	 * @return
	 */
	private YxSoeDeatilDTO Objetc2YxSoeDeatilDTO(Object obj){
		YxSoeDeatilDTO result=new YxSoeDeatilDTO();
		Object[] objs=(Object[])obj;
		result.setOccurTime(objs[0]==null?null:(DateUtil.getStringDate((Date)objs[0], DateUtil.pattern_ymdhms)));
		result.setSoeTime(objs[1]==null?null:(DateUtil.getStringDate((Date)objs[1], DateUtil.pattern_ymdhms)+"."+objs[2].toString()));
		result.setBreakerName(objs[3]==null?null:objs[3].toString());
		result.setActionStatus(objs[4]==null?null:objs[4].toString());
		result.setContent(objs[5]==null?null:objs[5].toString());
		result.setFaceId(objs[6]==null?null:objs[6].toString());
		return result;
	}
	
	/**
	 * 获取指定时间上下时间 dates[0] 上？分钟 ，dates[1] 下？分钟
	 * 
	 * @param date
	 * @return
	 */
	private Date[] getnearlyDates(Date date) {
		int temp=5;
		SystemParameter param = pc.get(ParamDesc.EMS_SEARCH_DEVIATION);
		if(null!=param){
			if(StringUtils.isNotEmpty(param.getValue())){
				temp=Integer.parseInt(param.getValue());
			}
		}
		Date[] result = new Date[2];
		DateTime dateTime = new DateTime(date);
		result[0] = dateTime.minusMinutes(temp).toDate();
		result[1] = dateTime.plusMinutes(temp).toDate();
		return result;
	}
	
	/**
	 * 生成sql
	 * @param size
	 * @return
	 */
	private String getFaceIdSql(int size){
		StringBuilder result=new StringBuilder();
		if(size==0){
			return result.toString();
		}
		result.append(" AND ( ");
		for(int i=0;i<size;i++){
			result.append( "t.FAC_ID =? OR ");
		}
		String temp=result.toString();
		temp=temp.substring(0, temp.lastIndexOf("OR"));
		temp=temp+") ";
		return temp;
	}

}
